<?php
namespace app\common\logic\cast;


use app\common\model\ad\Ads;
use app\common\model\ad\Rule;
use app\common\utils\Utils;
use fast\Http;
use think\Cache;
use think\Db;
use think\exception\ValidateException;
use think\Log;
use think\View;

/**
 * Created by PhpStorm.
 * User: yangchunfu
 * Date: 2019/12/24
 * Time: 4:36 PM
 * 栏目
 */

abstract class Base
{
    protected $options = [
        'apikey' => 'pyNLmuYuhi7Ua2Jj4SpaAwS2L6ri46q2ZxIdiwBtVVjdnWwexp0mO42MB7dnTQj4'
    ];
    protected $apiHref = null;
    protected $tag = '';
    static $cacheTime = 5 * 60;  //缓存5分钟
    protected $lastPage = '';
    public function __construct($options, $tag = '')
    {
        $this->options = array_merge($this->options, $options);
        $this->tag = $tag;
    }

    /**
     * 调用接口
     * @param mixed $options
     */
    public function get($options = []) {
        // TODO: Implement post() method.
        $options = array_merge($this->options, $options);
        $res = Http::get($this->apiHref, $options);
        $res = json_decode($res, true);
        if (!is_array($res)) {
            return [];
        }

        return $this->processData($res);
    }

    public function cache($data = [], $refresh = false) {
        $class = get_called_class();
        $page = isset($this->options['pageToken']) ? $this->options['pageToken'] : 1;
        $name = MD5($class . '-' .$page);
        $cache_data = Cache::get($name);
        if ($refresh === true) {
            Cache::tag('__CAST_NEWS__')->set($name, $data, self::$cacheTime);
            return $data;
        }
        if ($cache_data) {
            return $cache_data;
        }

        return true;
    }

    public function processData($data = []) {
        $res = isset($data['data']) ? $data['data'] : [];
        //publishDate id url title imageUrls(非必须)
        if (!is_array($res)) {
            throw new ValidateException('未抓取到数据');
        }
        $insert = [];
        foreach ($res as $k => $v) {
            try {
                $temp = $this->getField($v);
                if ($this->isRight($temp) && $temp){
                    array_push($insert, $temp);
                } else {
                    continue;
                }
            } catch (\Exception $e) {
                continue;
            }
        }
        $this->add($insert);
        $data['data'] = $insert;
        return $insert;
    }

    //过滤方法
    private function isRight($temp) {

        if (!isset($temp['imageUrls']) || !$temp['imageUrls']) {
            return false;
        }

        //图片链接过滤
        $nohref = config('site.nohref');
        if (in_array($temp['imageUrls'], $nohref)) {
            return false;
        }

        return true;
    }

    abstract public function getField($v);
    /**插入广告*/

    /**
     * 写入数据库方法
     */
    public function add($data) {
        //标示是类名小写
        if (!$this->tag) {
            throw new ValidateException('标识必须传递');
        }
        //首先判断是否已经写入数据库
        $db = Db::name('self_news');
        foreach ($data as $k => $v) {
            try {
                if ($db->where(['news_id' => $v['news_id']])->whereOr([
                        'title' => $v['title']
                    ])->count() > 0) {
                    continue;
                }
                $v['tag'] = $this->tag;
                $start = time() - 6 * 3600;
                $v['rand'] = rand($start, time());
                $v['createtime'] = time();
                $db->insert($v);
            } catch (\Exception $e) {
                Log::write($e->getMessage(), 'insertnews');
            }
        }

        return true;
    }


    //$row 代表每一页数量
    public function getList($row) {
        $db = Db::name('self_news');
        $page = input('page/d', 1);
        $refresh = input('refresh', 0); //0代表非下拉刷新 1代表是
        if ($page == 1 && $refresh) {
            //获取今天的id, 然后再获取其他的
            $ids = $db->orderRaw('rand()')
                ->where(['tag' => $this->tag])
                ->whereTime('publishDate', 'today')
                ->limit($row)
                ->column('id');
            if (count($ids) < $row) {
                $times = Utils::time_format(time(), 'Y-m-d');
                //从其他时间获取
                $otherIds = $db->orderRaw('rand()')
                    ->where(['tag' => $this->tag])
                    ->whereTime('publishDate', '<', $times)
                    ->limit($row - count($ids))
                    ->column('id');
                $ids = array_merge($ids, $otherIds);
            }
            //随机今天的消息
            $list = $db->where(['tag' => $this->tag, 'id' => ['in', $ids]])
                ->paginate($row)
                ->each(function ($item, $key) {
                    $item['publishDate'] = Utils::time_format($item['publishDate']);
                    $item['imageUrls'] = cdnurl($item['imageUrls'], true);

                    return $item;
                });
            //如果获取的数据小于row 那么从其他地方随机
        } else {
            $list = $db->where(['tag' => $this->tag])
                ->order('publishDate desc')
                ->paginate($row)
                ->each(function ($item, $key) {
                    $item['publishDate'] = Utils::time_format($item['publishDate']);
                    $item['imageUrls'] = cdnurl($item['imageUrls'], true);
                    return $item;
                });
        }

        return $list;
    }

}